﻿using System;
using System.Collections;
using System.DirectoryServices;
/***
*最近在和电信做一些接口的时候需要用到动态创建虚拟目录,
*搞了两天,不知道为什么同样的代码在控制台或其它的方法来创建是没问题OK的,
*但只要用web的方法来创建就会有问题,后来最终确认是权限的问题,
*但我IIS的权限也给管理员的还是不可以,后面才知道,
*原来只要在web.config里面加上<identity impersonate="true" userName=用户名 password=密码 />
*或<identity impersonate="true"/>这样也可以
 *使用案例：
 * IISManager iisManager = new IISManager("172.16.22.167", "默认网站");
    iisManager.Connect();
    VirtualDirectory vd=new VirtualDirectory("meihua.info","E:/Solution/MDCenter.root/MDCenter/PrecompiledWeb/MHMD.Web");
    //iisManager.Create(vd);
    iisManager.Delete("meihua.info");
    iisManager.Close();
*/
namespace Common.Net
{
    /// <summary>
    /// IISManager 的摘要说明。
    /// </summary>
    public class IISManager
    {
        //定义需要使用的
        private string _server, _website, _AnonymousUserPass, _AnonymousUserName;
        private VirtualDirectories _virdirs;
        protected DirectoryEntry rootfolder;
        private bool _batchflag;

        #region 默认构造方法 public OperationIIS()
        /// <summary>
        /// 默认构造方法
        /// 默认为默认站点，本机操作
        /// </summary>
        public IISManager()
        {
            //默认情况下使用localhost，即访问本地机
            _server = "localhost";
            _website = "1";
            _batchflag = false;
        }
        #endregion

        #region 构造方法：重载public OperationIIS(string strServer)
        /// <summary>
        /// 构造方法：重载
        /// </summary>
        /// <param name="strServer"></param>
        public IISManager(string strServer)
        {
            _server = strServer;
            _website = "1";
            _batchflag = false;
        }
        #endregion

        #region 构造方法：重载 public OperationIIS(string server, string websiteName)
        /// <summary>
        /// 构造方法：重载
        /// </summary>
        /// <param name="server"></param>
        /// <param name="websiteName"></param>
        public IISManager(string server, string websiteName)
        {
            _server = server;
            GetWebSiteID(websiteName);
        }
        #endregion

        #region 获得站点ID public void GetWebSiteID(string websiteName)
        /// <summary>
        /// 根据站点名字获得站点ID
        /// </summary>
        /// <param name="websiteName"></param>
        private void GetWebSiteID(string websiteName)
        {
            DirectoryEntry site = new DirectoryEntry("IIS://" + _server + "/W3SVC");
            foreach (DirectoryEntry item in site.Children)
            {
                if (item.SchemaClassName == "IIsWebServer" && item.Properties["ServerComment"][0].ToString() == websiteName)
                {
                    _website = item.Name;
                }
            }
        }
        #endregion

        #region 定义公共属性 public void get_AnonymousUser()
        /// <summary>
        /// 定义公共属性
        /// </summary>
        public void get_AnonymousUser()
        {
            _AnonymousUserPass = "IUSR_DEVE-SERVER";
            _AnonymousUserName = "IUSR_DEVE-SERVER";
            VirtualDirectory vDir;
            try
            {
                Hashtable myList = _virdirs;
                IDictionaryEnumerator myEnumerator = myList.GetEnumerator();
                while (myEnumerator.MoveNext())
                {
                    vDir = (VirtualDirectory)myEnumerator.Value;
                    if (vDir.AnonymousUserName != "" && vDir.AnonymousUserPass != "")
                    {
                        _AnonymousUserName = vDir.AnonymousUserName;
                        _AnonymousUserPass = vDir.AnonymousUserPass;
                        break;
                    }
                }
            }
            catch
            {
                _AnonymousUserPass = "IUSR_DEVE-SERVER";
                _AnonymousUserName = "IUSR_DEVE-SERVER";
            }
        }
        #endregion

        #region 匿名用户名 public string AnonymousUserName
        /// <summary>
        /// 匿名用户名
        /// </summary>
        public string AnonymousUserName
        {
            get { return _AnonymousUserName; }
            set { _AnonymousUserName = value; }
        }
        #endregion

        #region 匿名密码 public string AnonymousUserPass
        /// <summary>
        /// 匿名密码
        /// </summary>
        public string AnonymousUserPass
        {
            get { return _AnonymousUserPass; }
            set { _AnonymousUserPass = value; }
        }
        #endregion

        #region IP或计算机名 public string Server
        /// <summary>
        ///Server属性定义访问机器的名字，可以是IP与计算名 
        /// </summary>
        public string Server
        {
            get { return _server; }
            set { _server = value; }
        }
        #endregion

        #region 站点ID public string WebSite

        /// <summary>
        ///WebSite属性定义，为一数字，为方便，使用string 
        ///一般来说第一台主机为1,第二台主机为2，依次类推
        ///可以理解为网站ID
        /// </summary>
        public string WebSite
        {
            get { return _website; }
            set { _website = value; }
        }
        #endregion

        #region 虚拟目录的名字 public VirtualDirectories VirDirs
        /// <summary>
        /// 虚拟目录的名字
        /// </summary>
        public VirtualDirectories VirDirs
        {
            get { return _virdirs; }
            set { _virdirs = value; }
        }
        #endregion

        #region 连接服务器 public void Connect()
        ///<summary>
        ///连接服务器
        ///</summary>
        public void Connect()
        {
            ConnectToServer();
        }
        #endregion

        #region 重载连接服务器 public void Connect(string strServer)
        /// <summary>
        /// 重载
        /// </summary>
        /// <param name="strServer"></param>
        public void Connect(string strServer)
        {
            _server = strServer;
            ConnectToServer();
        }
        #endregion

        #region 重载连接服务器 public void Connect(string strServer, string strWebSite)
        /// <summary>
        /// 重载
        /// </summary>
        /// <param name="strServer"></param>
        /// <param name="strWebSite"></param>
        public void Connect(string strServer, string strWebSite)
        {
            _server = strServer;
            _website = strWebSite;
            ConnectToServer();
        }
        #endregion

        #region 判断是否存这个虚拟目录 public bool Exists(string strVirdir)
        /// <summary>
        /// 判断是否存这个虚拟目录
        /// </summary>
        /// <param name="strVirdir"></param>
        /// <returns>bool</returns>
        public bool Exists(string strVirdir)
        {
            return _virdirs.Contains(strVirdir);
        }
        #endregion

        #region 添加一个虚拟目录 public bool Create(VirtualDirectory newdir)
        /// <summary>
        /// 添加一个虚拟目录
        /// </summary>
        /// <param name="newdir"></param>
        /// <returns></returns>
        public bool Create(VirtualDirectory newdir)
        {
            //string strPath = "IIS://" + _server + "/W3SVC/" + _website + "/ROOT/" + newdir.Name;
            if (!_virdirs.Contains(newdir.Name) || _batchflag)
            {
                try
                {
                    //加入到ROOT的Children集合中去
                    DirectoryEntry newVirDir = rootfolder.Children.Add(newdir.Name, "IIsWebVirtualDir");
                    newVirDir.Invoke("AppCreate", true);
                    newVirDir.CommitChanges();
                    rootfolder.CommitChanges();
                    //然后更新数据
                    UpdateDirInfo(newVirDir, newdir);
                    return true;
                }
                catch (Exception ee)
                {
                    //throw new Exception(ee.ToString());
                    return false;
                }
            }
            else
            {
                return true;
                //throw new Exception("This virtual directory is already exist.");
            }
        }
        #endregion

        #region 得到一个虚拟目录 public VirtualDirectory GetVirDir(string strVirdir)
        /// <summary>
        /// 得到一个虚拟目录
        /// </summary>
        /// <param name="strVirdir"></param>
        /// <returns></returns>
        public VirtualDirectory GetVirDir(string strVirdir)
        {
            VirtualDirectory tmp = null;
            if (_virdirs.Contains(strVirdir))
            {
                tmp = _virdirs.Find(strVirdir);
                ((VirtualDirectory)_virdirs[strVirdir]).flag = 2;
            }
            else
            {
                //throw new Exception("This virtual directory is not exists");
            }
            return tmp;
        }
        #endregion

        #region 更新一个虚拟目录 public void Update(VirtualDirectory dir)
        /// <summary>
        /// 更新一个虚拟目录
        /// </summary>
        /// <param name="dir"></param>
        public void Update(VirtualDirectory dir)
        {
            //判断需要更改的虚拟目录是否存在
            if (_virdirs.Contains(dir.Name))
            {
                DirectoryEntry ode = rootfolder.Children.Find(dir.Name, "IIsWebVirtualDir");
                UpdateDirInfo(ode, dir);
            }
            else
            {
                //throw new Exception("This virtual directory is not exists.");
            }
        }
        #endregion

        #region 删除一个虚拟目录 public void Delete(string strVirdir)
        /// <summary>
        /// 删除一个虚拟目录
        /// </summary>
        /// <param name="strVirdir"></param>
        public void Delete(string strVirdir)
        {
            if (_virdirs.Contains(strVirdir))
            {
                object[] paras = new object[2];
                paras[0] = "IIsWebVirtualDir"; //表示操作的是虚拟目录
                paras[1] = strVirdir;
                rootfolder.Invoke("Delete", paras);
                rootfolder.CommitChanges();
            }
            else
            {
                //throw new Exception("Can''t delete " + strVirdir + ",because it isn''t exists.");
            }
        }
        #endregion

        #region 批量更新 public void UpdateBatch()
        /// <summary>
        /// 批量更新
        /// </summary>
        public void UpdateBatch()
        {
            BatchUpdate(_virdirs);
        }
        #endregion

        #region 批量更新：重载public void UpdateBatch(VirtualDirectories vds)
        /// <summary>
        /// 批量更新：重载
        /// </summary>
        /// <param name="vds"></param>
        public void UpdateBatch(VirtualDirectories vds)
        {
            BatchUpdate(vds);
        }
        #endregion

        #region 关闭服务器 public void Close()
        ///<summary>
        ///关闭服务器
        ///</summary>
        public void Close()
        {
            _virdirs.Clear();
            _virdirs = null;
            rootfolder.Dispose();
        }
        #endregion

        #region 连接服务器:私有private void ConnectToServer()
        /// <summary>
        /// 连接服务器:私有方法
        /// </summary>

        private void ConnectToServer()
        {
            string strPath = "IIS://" + _server + "/W3SVC/" + _website + "/ROOT";
            try
            {
                this.rootfolder = new DirectoryEntry(strPath);
                _virdirs = GetVirDirs(this.rootfolder.Children);
            }
            catch (Exception e)
            {
                //throw new Exception("Can''t connect to the server ["+ _server +"] ...",e);
            }
        }
        #endregion

        #region 执行批量更新:私有private void BatchUpdate(VirtualDirectories vds)
        /// <summary>
        /// 执行批量更新:私有
        /// </summary>
        /// <param name="vds"></param>
        private void BatchUpdate(VirtualDirectories vds)
        {
            _batchflag = true;
            foreach (object item in vds.Values)
            {
                VirtualDirectory vd = (VirtualDirectory)item;
                switch (vd.flag)
                {
                    case 0:
                        break;
                    case 1:
                        Create(vd);
                        break;
                    case 2:
                        Update(vd);
                        break;
                }
            }
            _batchflag = false;
        }
        #endregion

        #region 更新东东：私有private void UpdateDirInfo(DirectoryEntry de, VirtualDirectory vd)
        /// <summary>
        /// 更新东东：私有
        /// </summary>
        /// <param name="de"></param>
        /// <param name="vd"></param>
        private void UpdateDirInfo(DirectoryEntry de, VirtualDirectory vd)
        {
            de.Properties["AnonymousUserName"][0] = vd.AnonymousUserName;
            de.Properties["AnonymousUserPass"][0] = vd.AnonymousUserPass;
            de.Properties["AccessRead"][0] = vd.AccessRead;
            de.Properties["AccessExecute"][0] = vd.AccessExecute;
            de.Properties["AccessWrite"][0] = vd.AccessWrite;
            de.Properties["AuthBasic"][0] = vd.AuthBasic;
            de.Properties["AuthNTLM"][0] = vd.AuthNTLM;
            de.Properties["ContentIndexed"][0] = vd.ContentIndexed;
            de.Properties["EnableDefaultDoc"][0] = vd.EnableDefaultDoc;
            de.Properties["EnableDirBrowsing"][0] = vd.EnableDirBrowsing;
            de.Properties["AccessSSL"][0] = vd.AccessSSL;
            de.Properties["AccessScript"][0] = vd.AccessScript;
            de.Properties["DefaultDoc"][0] = vd.DefaultDoc;
            de.Properties["Path"][0] = vd.Path;
            de.CommitChanges();
        }
        #endregion

        #region 获取虚拟目录集合：私有private VirtualDirectories GetVirDirs(DirectoryEntries des)
        /// <summary>
        /// 获取虚拟目录集合：私有
        /// </summary>
        /// <param name="des"></param>
        /// <returns></returns>
        private VirtualDirectories GetVirDirs(DirectoryEntries des)
        {
            VirtualDirectories tmpdirs = new VirtualDirectories();
            foreach (DirectoryEntry de in des)
            {
                if (de.SchemaClassName == "IIsWebVirtualDir")
                {
                    VirtualDirectory vd = new VirtualDirectory();
                    vd.Name = de.Name;
                    vd.AccessRead = (bool)de.Properties["AccessRead"][0];
                    vd.AccessExecute = (bool)de.Properties["AccessExecute"][0];
                    vd.AccessWrite = (bool)de.Properties["AccessWrite"][0];
                    vd.AnonymousUserName = (string)de.Properties["AnonymousUserName"][0];
                    vd.AnonymousUserPass = (string)de.Properties["AnonymousUserName"][0];
                    vd.AuthBasic = (bool)de.Properties["AuthBasic"][0];
                    vd.AuthNTLM = (bool)de.Properties["AuthNTLM"][0];
                    vd.ContentIndexed = (bool)de.Properties["ContentIndexed"][0];
                    vd.EnableDefaultDoc = (bool)de.Properties["EnableDefaultDoc"][0];
                    vd.EnableDirBrowsing = (bool)de.Properties["EnableDirBrowsing"][0];
                    vd.AccessSSL = (bool)de.Properties["AccessSSL"][0];
                    vd.AccessScript = (bool)de.Properties["AccessScript"][0];
                    vd.Path = (string)de.Properties["Path"][0];
                    vd.flag = 0;
                    vd.DefaultDoc = (string)de.Properties["DefaultDoc"][0];
                    tmpdirs.Add(vd.Name, vd);
                }
            }
            return tmpdirs;
        }
        #endregion

        #region 创建和删除主机头名

        public void AddHostHeader(string domain)
        {
            DirectoryEntry site = new DirectoryEntry("IIS://" + _server + "/W3SVC/" + _website);

            PropertyValueCollection serverBindings = site.Properties["ServerBindings"];
            string headerStr = string.Format("{0}:{1}:{2}", null, 80, domain);
            if (!serverBindings.Contains(headerStr))
            {
                serverBindings.Add(headerStr);
            }
            site.CommitChanges();
        }
        /// <summary>
        /// DirectoryEntry site = new DirectoryEntry("IIS://172.16.22.109/W3SVC/1/root");
        /// 说明:
        /// siteid，默认站点是1，对于非默认站点，通过查看站点日志文件名就可以知道。
        ///或者直接查看文件C:\WINDOWS\system32\inetsrv\MetaBase.xml
        ///如果提示没有访问权限，请尝试使用虚拟帐号：
        ///<identity impersonate="true" userName="managerisdavid.weihw" password="@#$%&amp;%#$%sdfgsdaf34756" />
        /// </summary>
        /// <param name="siteid"></param>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="domain"></param>
        public void AddHostHeader(int port, string domain)//增加主机头（端口.域名）
        {
            DirectoryEntry site = new DirectoryEntry("IIS://" + _server + "/W3SVC/" + _website);
            PropertyValueCollection serverBindings = site.Properties["ServerBindings"];
            string headerStr = string.Format("{0}:{1}:{2}", _server, port, domain);
            if (!serverBindings.Contains(headerStr))
            {
                serverBindings.Add(headerStr);
            }
            site.CommitChanges();
        }

        public void DeleteHostHeader(string domain)
        {
            DirectoryEntry site = new DirectoryEntry("IIS://" + _server + "/W3SVC/" + _website);

            PropertyValueCollection serverBindings = site.Properties["ServerBindings"];
            string headerStr = string.Format("{0}:{1}:{2}", null, 80, domain);
            if (serverBindings.Contains(headerStr))
            {
                serverBindings.Remove(headerStr);
            }
            site.CommitChanges();
        }

        public void DeleteHostHeader(int port, string domain)//删除主机头（端口.域名）
        {
            DirectoryEntry site = new DirectoryEntry("IIS://" + _server + "/W3SVC/" + _website);
            PropertyValueCollection serverBindings = site.Properties["ServerBindings"];
            string headerStr = string.Format("{0}:{1}:{2}", _server, port, domain);
            if (serverBindings.Contains(headerStr))
            {
                serverBindings.Remove(headerStr);
            }
            site.CommitChanges();
        }


        #endregion


    }


    #region VirtualDirectory类 private class VirtualDirectory
    /// <summary>
    /// VirtualDirectory类
    /// </summary>
    public class VirtualDirectory
    {
        private bool _read, _execute, _script, _ssl, _write, _authbasic, _authntlm, _indexed, _endirbrow, _endefaultdoc;
        private string _ausername, _auserpass, _name, _path;
        private int _flag;
        private string _defaultdoc;

        /// <summary>
        /// 构造函数
        /// </summary>
        public VirtualDirectory()
        {
            SetValue();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sVirDirName">虚拟路径名</param>
        public VirtualDirectory(string sVirDirName)
        {
            SetValue();
            _name = sVirDirName;
        }
        public VirtualDirectory(string sVirDirName, string strPhyPath)
        {
            SetValue();
            _name = sVirDirName;
            _path = strPhyPath;
        }
        /// <summary>
        /// 创建一个虚拟路径实体
        /// </summary>
        /// <param name="sVirDirName">虚拟路径; </param>
        /// <param name="strPhyPath">物理路径( physics Path)</param>
        /// <param name="AnonymousUser"></param>
        public VirtualDirectory(string sVirDirName, string strPhyPath, string[] AnonymousUser)
        {
            SetValue();
            _name = sVirDirName;
            _path = strPhyPath;
            _ausername = AnonymousUser[0];
            _auserpass = AnonymousUser[1];
        }

        private void SetValue()
        {
            _read = true;
            _execute = false;
            _script = true;
            _ssl = false;
            _write = false;
            _authbasic = false;
            _authntlm = true;
            _indexed = true;
            _endirbrow = false;
            _endefaultdoc = true;
            _flag = 1;
            _defaultdoc = "default.html,default.htm,default.aspx,default.asp,index.htm";
            _path = "C:\\";
            _ausername = "IUSR_DEVE-SERVER";
            _auserpass = "IUSR_DEVE-SERVER";
            _name = "";
        }

        #region 义属性,IISVirtualDir太多属性了
        ///<summary>
        ///定义属性,IISVirtualDir太多属性了
        ///我只搞了比较重要的一些，其它的大伙需要的自个加吧。
        ///</summary>
        public int flag
        {
            get { return _flag; }
            set { _flag = value; }
        }

        public bool AccessRead
        {
            get { return _read; }
            set { _read = value; }
        }

        public bool AccessWrite
        {
            get { return _write; }
            set { _write = value; }
        }

        public bool AccessExecute
        {
            get { return _execute; }
            set { _execute = value; }
        }

        public bool AccessSSL
        {
            get { return _ssl; }
            set { _ssl = value; }
        }

        public bool AccessScript
        {
            get { return _script; }
            set { _script = value; }
        }

        public bool AuthBasic
        {
            get { return _authbasic; }
            set { _authbasic = value; }
        }

        public bool AuthNTLM
        {
            get { return _authntlm; }
            set { _authntlm = value; }
        }

        public bool ContentIndexed
        {
            get { return _indexed; }
            set { _indexed = value; }
        }

        public bool EnableDirBrowsing
        {
            get { return _endirbrow; }
            set { _endirbrow = value; }
        }

        public bool EnableDefaultDoc
        {
            get { return _endefaultdoc; }
            set { _endefaultdoc = value; }
        }

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public string Path
        {
            get { return _path; }
            set { _path = value; }
        }

        public string DefaultDoc
        {
            get { return _defaultdoc; }
            set { _defaultdoc = value; }
        }

        public string AnonymousUserName
        {
            get { return _ausername; }
            set { _ausername = value; }
        }

        public string AnonymousUserPass
        {
            get { return _auserpass; }
            set { _auserpass = value; }
        }
        #endregion
    }
    #endregion


    #region 集合VirtualDirectories, private class VirtualDirectories : Hashtable
    /// <summary>
    /// 集合VirtualDirectories
    /// </summary>
    public class VirtualDirectories : Hashtable
    {
        public VirtualDirectories()
        {
        }
        //添加新的方法 
        public VirtualDirectory Find(string strName)
        {
            return (VirtualDirectory)this[strName];
        }
    }
    #endregion

}